<?php
Yii::import('littlecrm.CRMBaseController');

/**
 * authorizing operations controller
 */
class AuthController extends CRMBaseController {
    /**
     * action to show assign to user
     */
    public function actionAssigns() {
        $this->render('assigns');
    }
    /**
     * @see actionAssigns
     */
    public function actionIndex() {
        $this->actionAssigns();
    }

    /**
     * gets and shows assigns to user
     */
    public function actionShowAssigns() {
        $user_id = strip_tags($_POST['Users']['users_username']);
        if(!empty($user_id)) {
            $user = Users::model()->findByPk($user_id);
            $roles = Item::model()->findAssignmentsForUserById($user->users_username);
        }
        $this->renderPartial('showAssigns', array('rbac' => $roles, 'username' => $user->users_username));
    }

    /**
     * item overview
     */
    public function actionItems() {
        $itemModel = new Item();
        $result = $itemModel->findAll();
        if(!Yii::app()->request->isAjaxRequest) {
            $this->render('items', array('result' => $result, 'itemModel' => $itemModel));
        }
        else {
            $this->renderPartial('tabs/showItems', array('result' => $result, 'itemModel' => $itemModel), false, true);
        }
    }

    /**
     * cancels an operation e.g. create item
     */
    public function actionCancel() {
        $itemModel = new Item();
        $this->renderPartial('tabs/addItem', array('itemModel' => $itemModel), false, true);
    }

    /**
     * action to delete an item
     */
    public function actionDelete() {
        $id = Yii::app()->request->getParam('id',0);
        if($id !== Yii::app()->dbConfig->superUser) {
            $itemModel = new Item();
            $itemModel->deleteByPk($id);
        }
        $result = $itemModel->findAll();
        $this->renderPartial('tabs/showItems', array('itemModel' => $itemModel, 'result' => $result), false, true);

    }

    /**
     * edit an auth item
     */
    public function actionEdit() {
        $id = Yii::app()->request->getParam('id',0);
        $itemModel = Item::model()->findByPk($id);
        $this->renderPartial('tabs/editItem', array('itemModel' => $itemModel), false, true);
    }

    /**
     * create an auth item
     */
    public function actionCreate() {
        $itemModel = new Item();
        if(isset($_POST['Item'])) {
            $itemModel->attributes = $_POST['Item'];
            if($itemModel->save()) {
                $itemModel = new Item();
            }
            $this->renderPartial('tabs/addItem', array('itemModel' => $itemModel), false, true);
        }
    }

    /**
     * action to update an auth item
     */
    public function actionUpdate() {
        $id = Yii::app()->request->getParam('id',0);
        $itemModel = Item::model()->findByPk($id);
        if(isset($_POST['Item'])) {
            $itemModel->setOldName($id);
            $itemModel->setOldType($itemModel->type);
            $itemModel->attributes = $_POST['Item'];
            if($itemModel->save()) {
                $itemModel = new Item();
                $this->renderPartial('tabs/addItem', array('itemModel' => $itemModel), false, true);
            } else {
                $this->renderPartial('tabs/editItem', array('itemModel' => $itemModel), false, true);
            }
        }
    }

    /**
     * assign wrapper action
     */
    public function actionAssign() {
        $user_id = (isset($_POST['Users']['users_username'])) ? strip_tags($_POST['Users']['users_username']) : '';
        $itemModel = new Item();
        $data['userAssignedRoles'] = array();
        $data['userNotAssignedRoles'] = array();
        $data['roleAssignedTasks'] = array();
        $data['roleNotAssignedTasks'] = array();
        $data['taskAssignedOperations'] = array();
        $data['taskNotAssignedOperations'] = array();
        $data["assign"] = array("disabled"=>true);
        $data["revoke"] = array("disabled"=>true);

        $auth = Yii::app()->authManager;
        $authItemAssignName = isset($_POST['Item']['name']['assign']) ? $_POST['Item']['name']['assign'] : "";
        $assBizRule = isset($_POST['Assignments']['bizrule']) ? $_POST['Assignments']['bizrule'] : "";
        $assData = isset($_POST['Assignments']['data']) ? $_POST['Assignments']['data'] : "";
        $authItemRevokeName = isset($_POST['Item']['name']['revoke']) ? $_POST['Item']['name']['revoke'] : "";
        $authItemName = isset($_POST['ItemDummy']['name']) ? $_POST['ItemDummy']['name'] : "";
        $assItemName = isset($_POST['Assignments']['itemname']) ? $_POST['Assignments']['itemname'] : "";

        $assignRoles = Yii::app()->request->getParam('assignRoles',0);
        $revokeRoles = Yii::app()->request->getParam('revokeRoles',0);
        $assignTasks = Yii::app()->request->getParam('assignTasks',0);
        $revokeTasks = Yii::app()->request->getParam('revokeTasks',0);
        $assignOperations = Yii::app()->request->getParam('assignOperations',0);
        $revokeOperations = Yii::app()->request->getParam('revokeOperations',0);
        if($revokeRoles && is_array($authItemRevokeName)) {
            $revoke = Assignments::model()->revokeAssignmentsByUserId($user_id, $authItemRevokeName);
        } elseif($assignRoles && is_array($authItemAssignName)) {
            $assign = Assignments::model()->assignAssignmentsByUserId($user_id, $authItemAssignName);
        } elseif ($assignTasks && is_array($authItemAssignName)) {
            $auth = Yii::app()->authManager;
            foreach ($authItemAssignName as $child) {
                $auth->addItemChild($authItemName, $child);
            }
        } elseif($revokeTasks && is_array($authItemRevokeName)) {
            $auth = Yii::app()->authManager;
            foreach ($authItemRevokeName as $child) {
                $auth->removeItemChild($authItemName, $child);
            }
        } elseif($revokeOperations && is_array($authItemRevokeName)) {
            $auth = Yii::app()->authManager;
            foreach ($authItemRevokeName as $child) {
                $auth->removeItemChild($assItemName, $child);
            }
        } elseif($assignOperations && is_array($authItemAssignName)) {
            $auth = Yii::app()->authManager;
            foreach($authItemAssignName as $child) {
                $auth->addItemChild($assItemName, $child);
            }
        }


        if(!Yii::app()->request->isAjaxRequest) {
            $this->render('assign',array(
                    'itemModel'=>$itemModel,
                    'message'=>'',
                    'userid'=>$user_id,
                    'data'=>$data
            ));
        }
        else {
            if(!empty($user_id)) {
                $this->_renderUserAjax($user_id);
            } elseif($assignTasks || $revokeTasks) {
                $this->_renderRoleAjax($authItemName);
            } elseif($revokeOperations || $assignOperations) {
                $this->_renderTaskAjax($assItemName);
            }
        }
    }

    /**
     *
     * @param string $what
     * @param string $to
     * @param <type> $identitifier
     */
    protected function _renderAjaxPartial($what, $to, $identitifier) {
        $itemModel = new Item();
        $findAssignMethodName = 'findAssigned'.ucfirst($to).'By'.ucfirst($what);
        $findNotAssignMethodName = 'findNotAssigned'.ucfirst($to).'By'.ucfirst($what);
        $data[$what.'Assigned'.$to] = $itemModel->{$findAssignMethodName}($identitifier);
        $data[$what.'NotAssigned'.$to] = $itemModel->{$findNotAssignMethodName}($identitifier);
        if($data[$what.'Assigned'.$to] === array()) {
            $data['revoke'] = array("name"=>"revoke".ucfirst($what), "id"=>"revoke".ucfirst($what), "disabled"=>true);
        } else {
            $data['revoke'] = array("name"=>"revoke".ucfirst($what), "id"=>"revoke".ucfirst($what));
        }

        if($data[$what.'NotAssigned'.$to] === array()) {
            $data['assign'] = array("name"=>"assign".ucfirst($what), "id"=>"assign".ucfirst($what), "disabled"=>true);
        } else {
            $data['assign'] = array("name"=>"revoke".ucfirst($what), "id"=>"assign".ucfirst($what));
        }

        $this->renderPartial('application.modules.core.components.views.tabs.revokeAssignList', array(
                'itemModel' => $itemModel,
                'assign' => $data['assign'],
                'revoke' => $data['revoke'],
                'revokedData' => $data[$what.'NotAssigned'.$to],
                'assignedData' => $data[$what.'Assigned'.$to],
                'tab' => $to), false, true);

    }

    protected function _renderUserAjax($user_id) {
        $this->_renderAjaxPartial('user', 'roles', $user_id);
    }

    protected function _renderTaskAjax($itemName) {
        $this->_renderAjaxPartial('task', 'operations', $itemName);
    }

    protected function _renderRoleAjax($itemName) {
        $this->_renderAjaxPartial('role', 'tasks', $itemName);
    }

    public function actionShowTasks() {
        $itemName = strip_tags($_POST['ItemDummy']['name']);
        $this->_renderRoleAjax($itemName);
    }

    public function actionShowOperations() {
        $itemName = strip_tags($_POST['Assignments']['itemname']);
        $this->_renderTaskAjax($itemName);
    }

    public function actionShowRoles() {
        $user_id = strip_tags($_POST['Users']['users_username']);
        $this->_renderUserAjax($user_id);
    }

// -----------------------------------------------------------
// Uncomment the following methods and override them if needed
    /*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
    */
}